package com.rdxer.model;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.databind.type.TypeFactory;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.AttributeConverter;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 附件表
 */
@Entity
@Data
public class Attachment {

    @Id
    @JsonSerialize(using= ToStringSerializer.class)
    private Long id;
    @JsonSerialize(using= ToStringSerializer.class)
    private String uid;

    private String type;
    @Column(columnDefinition = "text")
    private String filename;
    @Column(columnDefinition = "text")
    private String url;
    @Column(columnDefinition = "text")
    @JsonIgnore
    private String putUrl;

    @JsonSerialize(using= ToStringSerializer.class)
    private Long createdDate;
    private String host;
    @Column(columnDefinition = "text")
    private String path;

    @NoArgsConstructor
    @Data
    public static class Converter implements AttributeConverter<Attachment,String> {

        ObjectMapper objectMapper = new ObjectMapper();

        @Override
        public String convertToDatabaseColumn(Attachment o) {
            try {
                return objectMapper.writeValueAsString(o);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                return null;
            }
        }

        @Override
        public Attachment convertToEntityAttribute(String s) {
            try {
                return objectMapper.readValue(s, Attachment.class);
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }
    }
    @NoArgsConstructor
    @Data
    public static class ListConverter implements AttributeConverter<List<Attachment>,String> {

        ObjectMapper objectMapper = new ObjectMapper();
        TypeFactory typeFactory = objectMapper.getTypeFactory();

        @Override
        public String convertToDatabaseColumn(List<Attachment> o) {
            try {
                return objectMapper.writeValueAsString(o);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                return "[]";
            }
        }

        @Override
        public List<Attachment> convertToEntityAttribute(String s) {
            try {
                return objectMapper.readValue(s, typeFactory.constructCollectionType(List.class, Attachment.class));
            } catch (IOException e) {
                e.printStackTrace();
                return new ArrayList<>();
            }
        }
    }
}
